package com.harmonyos.samples.utils;

import com.google.gson.*;
import com.harmonyos.samples.action.DemoTestAction;
import com.harmonyos.samples.constants.Constants;
import com.harmonyos.samples.view.PluginDialog;
import org.apache.http.client.methods.HttpGet;

import java.io.File;
import java.io.IOException;

import static com.harmonyos.samples.utils.InsertUtils.getFileNameFromUrl;

// 下载代码
public class GiteeApiClient {

    private final int fakeCount = 30;

    private int initCount = 0;

    private String gifPath;

    private String repositoryName;

    public GiteeApiClient() {
    }

    public void setGifPath(String gifPath) {
        this.gifPath = gifPath;
    }

    public void setRepositoryName(String caseRepositoriesInfo) {
        String repositoryName = getFileNameFromUrl(caseRepositoriesInfo);
        this.repositoryName = repositoryName.replace(".git", "");
        Constants.GITEE_REPO = this.repositoryName;
    }

    /**
     * 获取指定仓库中所有文件的 Raw URLs
     *
     * @param subPath 路径信息
     * @throws IOException           网络异常
     * @throws IllegalStateException API 返回错误
     */
    public void getAllFileRawUrls(String subPath, String localPath, String rootPath) throws IOException, InterruptedException {
        String path = ""; // 从根目录开始
        updateProgress("0%");
        fetchFilesRecursively(subPath, path, localPath);
        if (DemoTestAction.canDownload) {
            Thread.sleep(1000);
            updateProgress("0%");
        }
        if (subPath.equals("CommonAppDevelopment/feature/customdecoration/")) {
            String libPath = "https://gitee.com/harmonyos-cases/cases/raw/master/CommonAppDevelopment/libs/autobuilddecoration-1.0.2.tgz";
            File file = new File(rootPath + "/" + "libs");
            if (!file.exists()) {
                file.mkdirs();
            }
            HttpRequest.getInstance().download(libPath, rootPath + "/" + "libs/autobuilddecoration-1.0.2.tgz");
        }
    }

    private void fetchFilesRecursively(String subPath, String path, String localPath) {
        String homeUrl = String.format(Constants.BASE_URL, Constants.GITEE_OWNER, Constants.GITEE_REPO);
        String homePath = homeUrl + "/" + subPath + (path.isEmpty() ? "" : "/" + path);
        if (!DemoTestAction.canDownload) {
            return;
        }
        String url = homePath + Constants.TEST_ACCESS_TOKEN + PluginDialog.localRef;
        String result = HttpRequest.getInstance().executeGet(new HttpGet(url));
        if (result == null) {
            return;
        }
        JsonElement jsonElement = JsonParser.parseString(result);
        if (jsonElement.isJsonArray()) {
            JsonArray jsonArray = jsonElement.getAsJsonArray();
            for (JsonElement element : jsonArray) {
                JsonObject obj = element.getAsJsonObject();
                String type = obj.get("type").getAsString();
                String filePath = obj.get("path").getAsString();
                if ("file".equals(type)) {
                    String downloadUrl = obj.get("download_url").getAsString();
                    File temp = new File(localPath);
                    if (!temp.exists()) {
                        temp.mkdirs();
                    }
                    HttpRequest.getInstance().download(downloadUrl, localPath + "/" + obj.get("name").getAsString(), gifPath);
                    initCount = initCount + 1;
                    int progress = initCount * 100 / fakeCount;
                    if (progress >= 99) {
                        progress = 99;
                    }
                    updateProgress(progress + "%");
                } else if ("dir".equals(type)) {
                    // 递归处理子目录
                    fetchFilesRecursively(subPath + "/" + path, obj.get("name").getAsString(), localPath + "/" + obj.get("name").getAsString());
                }
            }
        } else if (jsonElement.isJsonObject()) {
            // 单个文件或目录
            JsonObject obj = jsonElement.getAsJsonObject();
            String type = obj.get("type").getAsString();
            String filePath = obj.get("path").getAsString();
            if ("file".equals(type)) {
                String downloadUrl = obj.get("download_url").getAsString();
                HttpRequest.getInstance().download(downloadUrl, localPath + filePath, gifPath);
                initCount = initCount + 1;
                int progress = initCount * 100 / fakeCount;
                if (progress >= 99) {
                    progress = 99;
                }
                updateProgress(progress + "%");
            } else if ("dir".equals(type)) {
                // 递归处理子目录
                fetchFilesRecursively(subPath + "/" + path, obj.get("name").getAsString(), localPath);
            }
        }
    }

    private void updateProgress(String progress) {
        if (DemoTestAction.progressWindow != null) {
            DemoTestAction.progressWindow.setText(String.format("下载中...%s", progress));
        }
    }

}
